package com.pengchuang.ACS.admin.boot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pengchuang.ACS.admin.api.dto.UserAuthDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengchuang.ACS.admin.boot.dao.SysRoleDao;
import com.pengchuang.ACS.admin.boot.dao.SysUserMapper;
import com.pengchuang.ACS.admin.boot.dao.SysUserRoleDao;
import com.pengchuang.ACS.admin.boot.entity.SysRoleEntity;
import com.pengchuang.ACS.admin.boot.entity.SysUser;
import com.pengchuang.ACS.admin.boot.entity.SysUserRoleEntity;
import com.pengchuang.ACS.admin.boot.service.ISysUserService;
import com.pengchuang.ACS.common.constant.SecurityConstants;
import com.pengchuang.ACS.common.utils.PageUtils;
import com.pengchuang.ACS.common.utils.Query;
import com.pengchuang.ACS.common.utils.R;
import com.pengchuang.ACS.common.utils.ResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author： 乐哥聊编程(全平台同号)
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private final SysRoleDao sysRoleDao;

    private final SysUserRoleDao sysUserRoleDao;

    public String UserWithAuth() throws UnsupportedEncodingException {
        // 查询用户角色 查询对应的权限
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String header = request.getHeader(SecurityConstants.JWT_PAYLOAD_KEY);
        header = URLDecoder.decode(header, "utf-8");
        Map map = JSONObject.parseObject(header, Map.class);
        Object username = map.get("user_name");
        return String.valueOf(username);
    }

    public Boolean isRoot(String username) {
        // 调用map查询用户信息
        List<String> userRole = this.baseMapper.getUserRole(username);
        // 查看如果是 root 管理员的话 级别最高
        for (String role : userRole) {
            if ("root".equals(role)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public UserAuthDTO getByUsername(String username) {
        UserAuthDTO userAuthInfo = this.baseMapper.getByPhone(username);
        return userAuthInfo;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        return null;
    }

    @Override
    public R queryPageWithAuth(Map<String, Object> params) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();

        try {
            String username = UserWithAuth();
            SysUser sysUser = this.baseMapper.selectOne(new QueryWrapper<SysUser>()
                    .eq("username" ,username));
            if (!isRoot(username)) {
                // 说明是具有所有权限的人
                sysUserQueryWrapper.eq("cell_id", sysUser.getCellId());
            }
        } catch (UnsupportedEncodingException e) {
            return R.error(ResultCode.PARAM_VALID_FAIL);
        }
        if (params.get("username") != null) {
            sysUserQueryWrapper.like("nickname", params.get("username") );
        }
        if (params.get("isOpen") != null) {
            sysUserQueryWrapper.like("is_open", params.get("isOpen") );
        }
        if (params.get("phone") != null) {
            sysUserQueryWrapper.like("phone", params.get("phone") );
        }
        IPage<SysUser> page = this.page(
                new Query<SysUser>().getPage(params),
                sysUserQueryWrapper
        );
        // 查询每个角色对应的角色信息 小区和role类型
        for (SysUser record : page.getRecords()) {
            Long roleId = sysUserRoleDao.selectOne(new QueryWrapper<SysUserRoleEntity>()
                    .eq("user_id", record.getId())).getRoleId();
            SysRoleEntity sysRoleEntity = sysRoleDao.selectById(roleId);
            record.setRoleName(sysRoleEntity.getName());
            record.setRoleId(sysRoleEntity.getId());
        }

        return R.ok().put("result", new PageUtils(page));
    }
}
